﻿(function () {
    "use strict";

    var propertycollection = {};
    var pIndex = 0;
    var current;
	var currentCategory;

    WinJS.UI.Pages.define("/pages/administrative/taskAddCategory.html", {
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            // TODO: Initialize the page here.
			AddProperty.addEventListener("MSPointerDown", onPointerDownAddProperty, false);
			AddProperty.addEventListener("MSPointerUp", onPointerUpAddProperty, false);
			AddProperty.addEventListener("click", addProperty, false);

			SavePropertySettings.addEventListener("click", changeProperty, false);
			AddCategoryButton.addEventListener("click", addNewCategory, false);
			SubmitCategoryButton.addEventListener("click", submitCatagory, false);
			document.getElementById("cmdAdd").addEventListener("click", addProperty, false);
			document.getElementById("cmdDelete").addEventListener("click", doClickDelete, false);
			document.getElementById("cmdEdit").addEventListener("click", doClickEdit, false);

            mainsection.style.opacity = "0";
            propertycollection = new WinJS.Binding.List();
            PropertyList.winControl.itemDataSource = propertycollection.dataSource;
            PropertyList.winControl.itemTemplate = PropertyTemplate;
            PropertyList.winControl.forceLayout();
			
            PropertyList.addEventListener("selectionchanged", itemSelect, false);
            // Hide selection group of commands
            CategoryAppBar.winControl.hideCommands(CategoryAppBar.querySelectorAll('.categoryBar'));
            CategoryAppBar.winControl.disabled = true;


            runEnterPageAnimation();

        }
    });

    function itemSelect(evt) {
        if (PropertyList.winControl.selection.count() == 0) {
            CategoryAppBar.winControl.disabled = true;
            CategoryAppBar.winControl.hideCommands(CategoryAppBar.querySelectorAll('.categoryBar'));
            CategoryAppBar.winControl.sticky = false;
            CategoryAppBar.winControl.hide();
        }
        else {
            CategoryAppBar.winControl.disabled = false;
            CategoryAppBar.winControl.showCommands(CategoryAppBar.querySelectorAll('.categoryBar'));
            CategoryAppBar.winControl.sticky = true;
            CategoryAppBar.winControl.show();
        }
    }

    function onPointerDownAddProperty(evt) {
        WinJS.UI.Animation.pointerDown(AddProperty);
    }

    function onPointerUpAddProperty(evt) {
        WinJS.UI.Animation.pointerUp(AddProperty);
    }


    function runEnterPageAnimation() {
        mainsection.style.overflow = "hidden";
        // Animate the application's entrance in the number of stages chosen by the user
        // Use the recommended offset by leaving the offset argument empty to get the best performance
        var enterContent;
        WinJS.Promise.timeout(2000);
        enterContent = WinJS.UI.Animation.enterContent(mainsection, null);

        enterContent.done(
            function () {
                mainsection.style.overflow = "auto";
            });
    }

    // Adds a new Property to the end of the collection
    function addProperty() {
        //Create the data for the Property
        var prop = generateProperty();
        propertycollection.push(prop);
    }

    // Delete Item
    function doClickDelete() {
        if (!CategoryAppBar.winControl.getCommandById("cmdAdd").hidden) {
            var listView = PropertyList.winControl;
            if (listView.selection.count() > 0) {
                var indices = listView.selection.getIndices();
                for (var i = indices.length - 1; i >= 0; i--) {
                    propertycollection.splice(indices[i], 1);
                }
            }
        }
        else
        {
            for (var i = 0; i < propertycollection.length ; i++)
                propertycollection.splice(i, 1);
            tbCategoryName.value = "";
            document.getElementById(current.id).parentElement.removeChild(document.getElementById(current.id));
        }
    }

    //Edit Item
    function doClickEdit(evt) {
        var listView = PropertyList.winControl;
        if (listView.selection.count() > 0) {
            var item = document.getElementById("PropertyTemplate");
            var indices = listView.selection.getIndices();
            inputName.value = propertycollection.slice(indices[0], indices[0] + 1)[0].Name;
            //document.getElementById("editFlyout").st
            document.getElementById("editFlyout").winControl.show(item);
        }
    }

    //Edit Item
    function changeProperty() {
        var listView = PropertyList.winControl;
        if (listView.selection.count() > 0) {
           var indices = listView.selection.getIndices();
           var item = document.getElementById("PropertyTemplate");
           propertycollection.slice(indices[0], indices[0] + 1)[0].Name = inputName.value;
           propertycollection.slice(indices[0], indices[0] + 1)[0].PType = selectType.value;
           document.getElementById("editFlyout").winControl.hide(item);
           PropertyList.winControl.forceLayout();
        }
    }

	function addNewCategory(){
		var propertyName = tbCategoryName.value;
		var category = {
			categoryName: propertyName
		} 

		if (propertyName.replace(" ", "_") == "" || propertyName.replace(" ", "_") == "_") {
		    var msg = new Windows.UI.Popups.MessageDialog("The defined Category has no name. Please enter a name", "Invalid Category definition");

		    msg.commands.append(new Windows.UI.Popups.UICommand("Ok"));

		    msg.defaultCommandIndex = 1;

		    msg.showAsync();
            
		    return;
		}
		else if (propertycollection.length == 0)
		{
		    var msg = new Windows.UI.Popups.MessageDialog("The defined Category has no properties. Please add a property to the Category", "Invalid Category definition");

		    msg.commands.append(new Windows.UI.Popups.UICommand("Ok"));

		    msg.defaultCommandIndex = 1;

		    msg.showAsync();

		    return;
		}

		 var templateElement = document.getElementById("NewCatagoryTemplate");
         var renderElement = document.getElementById("renderNewCategoryArea");
         renderElement.innerHTML = "";

		 templateElement.winControl.render(category)
                    .done(function (result) {
                        result.id = category.categoryName.replace(" ", "_");
                        currentCategory = result.id;
                        renderElement.appendChild(result);

                        document.getElementById(result.id).addEventListener("MSPointerDown", onPointerDownSelect, false);
                        document.getElementById(result.id).addEventListener("MSPointerUp", onPointerUpSelect, false);

                        GeneratedPropertyList.winControl.itemDataSource = propertycollection.dataSource;
                        GeneratedPropertyList.winControl.itemTemplate = PropertyTemplate;
                        GeneratedPropertyList.winControl.forceLayout();

                    });
	}

	function submitCatagory(){
		var listView = PropertyList.winControl;
		if(propertycollection.length == 0 || currentCategory == undefined)
		{
		    var msg = new Windows.UI.Popups.MessageDialog("The defined Category has no properties. Please add a property to the Category", "Invalid Category definition");

		    msg.commands.append(new Windows.UI.Popups.UICommand("Ok"));

		    msg.defaultCommandIndex = 1;

		    msg.showAsync();

		    return;
		}
		var stringArray = toStringArray(propertycollection.slice());
	    //first implementation with static webservice-address.
		var category = {
		    OrmName: currentCategory,
		    Definitions: JSON.stringify(stringArray)
		};
		var jsonParameter = JSON.stringify(category);
		$.post("http://localhost:9000/api/genrateCategory/1?jsonString=" + jsonParameter, function (data) {
				
		    var msg = new Windows.UI.Popups.MessageDialog("", "Test");

		    msg.commands.append(new Windows.UI.Popups.UICommand("Ok"));

		    msg.defaultCommandIndex = 1;

		    msg.showAsync();

		    return;
		});


	}

	function onPointerDownSelect(evt) {
	    WinJS.UI.Animation.pointerDown(evt.currentTarget);

	    var hasClass = WinJS.Utilities.hasClass(evt.currentTarget.children[0], "TaskAddCategoryFlexChildSelected");
	    if (!hasClass) {
	        WinJS.Utilities.addClass(evt.currentTarget.children[0], "TaskAddCategoryFlexChildSelected");
	        WinJS.Utilities.removeClass(evt.currentTarget.children[0], "TaskAddCategoryFlexChildItem");
	        current = evt.currentTarget;
	        CategoryAppBar.winControl.disabled = false;
	        CategoryAppBar.winControl.hideCommands(CategoryAppBar.querySelectorAll('.categoryBar'));
	        CategoryAppBar.winControl.showCommands(CategoryAppBar.querySelector('#cmdDelete'));
	        CategoryAppBar.winControl.sticky = true;
	        CategoryAppBar.winControl.show();
	    }
	    else {
	        WinJS.Utilities.removeClass(evt.currentTarget.children[0], "TaskAddCategoryFlexChildSelected");
	        WinJS.Utilities.addClass(evt.currentTarget.children[0], "TaskAddCategoryFlexChildItem");

	        CategoryAppBar.winControl.disabled = true;
	        CategoryAppBar.winControl.hideCommands(CategoryAppBar.querySelectorAll('.categoryBar'));
	        CategoryAppBar.winControl.sticky = false;
	        CategoryAppBar.winControl.hide();
	    }

	}

	function onPointerUpSelect(evt) {
	    WinJS.UI.Animation.pointerUp(evt.currentTarget);
	}

    // Generates a Property with a random letter and counter
    function generateProperty() {
        var prop = {
            Name: "New Property name",
            PType: "String",
            Counter: pIndex
        };
        pIndex++;

        return prop;
    }

    //Generates a JSON String Array
    function toStringArray(propertyArray)
    {
        if (propertyArray.length <= 0)
            return {};
        var stringArray = new Array(propertyArray.length);
        for (var i = 0; i < propertyArray.length; i++) {
            stringArray[i] = JSON.stringify(propertyArray[i]);
        }
        return stringArray;
    }
})();
